package com.tool.cn.use;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

/**
 * 操作文件
 * 
 * @author wangzh
 * 2016年11月1日 上午9:34:25
 */
public  final class FileUse{
	public String url;
	public String fileName;
	public FileUse(String url,String fileName){
		this.url=url;
		this.fileName=fileName;
	}
	
	/**
	 * 创建文件
	 */
	public boolean createFile(){
		File file=new File(url);
		if(!file.exists()){
			file.mkdirs();
		}
		return true;
	}
	
	/**
	 * 写入文件内容
	 * state：为true 追加文件内容  false 重新写入文件内容
	 */
	public boolean addData(String content,boolean state){
		try {
			BufferedWriter write=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(url+File.separatorChar+fileName,state),"utf-8"));
			write.write(content+System.getProperty("line.separator"));
			
			write.flush();
			write.close();
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}
	
	/**
	 * 获取文件内容
	 */
	public String findData(){
		try {
			BufferedReader buf=new BufferedReader(new InputStreamReader(new FileInputStream(url+File.separatorChar+fileName),"utf-8"));
			String context,cont="";
			while((context=buf.readLine())!=null){
				cont+=context;
			}
			buf.close();
			return cont;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return "";
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		}
	}
	
	
	/**
	 * 清空文件内容
	 */
	public boolean clearData(){
		return addData("", false);
	}
	
}
